package cn.cyh.queue_service.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration
@ConfigurationProperties(prefix = "cors")
@Data
public class CorsConfig {

    private String[] allowedOrigins;
    private String[] allowedMethods;
    private String[] allowedHeaders;
    private Boolean allowCredentials;
    private Long maxAge;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        
        // 允许的域
        if (allowedOrigins != null && allowedOrigins.length > 0) {
            for (String origin : allowedOrigins) {
                config.addAllowedOriginPattern(origin);
            }
        } else {
            config.addAllowedOriginPattern("*");
        }
        
        // 允许的方法
        if (allowedMethods != null && allowedMethods.length > 0) {
            for (String method : allowedMethods) {
                config.addAllowedMethod(method);
            }
        } else {
            config.addAllowedMethod("*");
        }
        
        // 允许的头
        if (allowedHeaders != null && allowedHeaders.length > 0) {
            for (String header : allowedHeaders) {
                config.addAllowedHeader(header);
            }
        } else {
            config.addAllowedHeader("*");
        }
        
        // 允许Cookie
        if (allowCredentials != null) {
            config.setAllowCredentials(allowCredentials);
        } else {
            config.setAllowCredentials(true);
        }
        
        // 预检请求的有效期
        if (maxAge != null) {
            config.setMaxAge(maxAge);
        } else {
            config.setMaxAge(3600L);
        }
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        
        return new CorsFilter(source);
    }
} 